package com.guzhi.service.sms;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.guzhi.utils.ThreadPool;

/**
 * 短信服务接口，使用spring xml方式配置，主要是为了注入具体的短信处理类
 * 
 * @author duanshao
 * 
 */
public class SmsService {

    private final Logger LOG = LoggerFactory.getLogger(SmsService.class);

    private List<SmsHandler> handlers;

    private static ThreadPool pool = new ThreadPool(5, "sms");

    /**
     * @param handlers
     */
    public void setHandlers(List<SmsHandler> handlers) {
        this.handlers = handlers;
    }

    /**
     * 发送短信
     * 
     * @param phone
     * @param content
     * @return
     */
    public boolean send(String phone, String content) {
        return sendHelper(phone, content, true);
    }

    private boolean sendHelper(final String phone, final String content, boolean retry) {
        final SmsHandler handler = getHandler();
        if (handler == null) {
            LOG.info("[send] no avaliable sms handler, phone:{}", phone);
            return false;
        }
        
        if (retry) {
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    int result = handler.send(phone, content);
                    if (result == SmsHandler.CODE_NO_BALANCE) {
                        // 账户余额不足，设置为不可用
                        LOG.info("[send] phone:{} handler:{} no balance", phone, handler.getClass().getName());
                        handler.setAlive(false);
                    } else if (result == SmsHandler.CODE_SUCCESS) {
                        System.out.println("SmsService........result=" + result);
                        LOG.info("[send] success phone:{} ", phone);
                        return;
                    } else if (result == SmsHandler.CODE_FAIL) {
                        LOG.info("[send] fail phone:{} ", phone);
                        // 增加接口调用失败次数
                        handler.addFails();
                    }
                    // 重新查找新的handler处理,不再重试
                    sendHelper(phone, content, false);
                }
            });
        }
        return true;
    }

    
    public SmsHandler getHandler() {
        for (SmsHandler handler : handlers) {
            if (handler.isAlive()) {
                return handler;
            }
        }
        return null;
    }

}
